// const Jimp = require("jimp");
// const fs = require("fs");
// const path = require("path");
import Jimp from "jimp";
import fs from "fs";
import path from "path";

window.onload = () => {
  document.getElementById("picMerge").addEventListener("click", picMerge);
};

async function picMerge() {
  const folderPath = "F:/Projects/我的工具库/图片整合/交易回顾";
  const picMerge = (imgPaths) => {
    const folderPath = path.dirname(imgPaths?.[0] ?? "");
    const pngs = imgPaths.filter((item) => item.match(".png"));
    // for (let png of pngs) {
    //   console.log("png", png);
    //   fs.unlink(png, () => {});
    // }
    console.log("pngs", pngs);
    Promise.all(
      pngs.map((png) => {
        return Jimp.read(png);
      })
    ).then((images) => {
      console.log("images", images);
      //   const image2 = await Jimp.read("3.png");
      // 假设两张图片大小相同，你可以直接合并
      // 如果大小不同，你可能需要调整它们的大小以匹配
      const imagesHeight = [];
      const imagesWidth = [];
      images.forEach((image) => {
        imagesHeight.push(image.bitmap.height);
        imagesWidth.push(image.bitmap.width);
      });
      const MaxWidth = imagesWidth.reduce((sum, item) => {
        return sum + item;
      }, 0);

      // 创建一个新的空白图像，宽度是两张图片之和，高度与单张图片相同
      const combinedImage = new Jimp(
        MaxWidth,
        Math.max.apply(null, imagesHeight),
        0x000000
      ); // 黑色背景

      let xCoord = 0;
      // 将图像复制到空白
      for (let i = 0; i < images.length; i++) {
        if (i !== 0) {
          xCoord += images[i - 1].bitmap.width;
        }
        combinedImage.composite(images[i], xCoord, 0, {
          mode: Jimp.BLEND_SOURCE_OVER,
          opacitySource: 1,
          opacityDest: 1,
        });
      }
      const folderArray = folderPath.split("\\");
      console.log("路径数组", folderArray);
      // 取数组最后一位
      const folder1 = folderArray[folderArray.length - 2] ?? "";
      const folder2 = folderArray[folderArray.length - 1] ?? "";
      console.log("路径1", folder1);
      console.log("路径2", folder2);
      // 将合并后的图像写入文件
      combinedImage.write(`${folderPath}/${folder1}_${folder2}_CB.png`);
    });
  };
  const toFolder = async (folderPath) => {
    const files = await fs.readdirSync(folderPath);
    const imgFormat = [".jpg", ".jpeg", ".png", ".svg"];
    const imgPaths = [];
    for (let file of files) {
      const filePath = path.join(folderPath, file);
      if (fs.statSync(filePath).isDirectory()) {
        // 进入目录，再次读取
        console.log("文件夹名", file);
        toFolder(filePath);
      } else {
        const extname = path.extname(file);
        if (imgFormat.includes(extname)) {
          console.log("文件路径", filePath);
          imgPaths.push(filePath);
        }
      }
    }
    if (imgPaths.length) {
      picMerge(imgPaths);
    }
  };
  await toFolder(folderPath);
}

// module.exports = picMerge;
